package cn.didi.feidi.androidorder.fragment.personal;


import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.reflect.TypeToken;
import com.jungly.gridpasswordview.GridPasswordView;

import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import cn.didi.feidi.androidorder.R;
import cn.didi.feidi.androidorder.api.Api;
import cn.didi.feidi.androidorder.api.ApiResponse;
import cn.didi.feidi.androidorder.api.ErrorEvent;
import cn.didi.feidi.androidorder.assembly.CommomDialog;
import cn.didi.feidi.androidorder.core.ActionCallbackListener;
import cn.didi.feidi.androidorder.core.AppActionRequest;
import cn.didi.feidi.androidorder.fragment.FeidiBaseFragment;
import cn.didi.feidi.androidorder.manager.UserManager;
import cn.didi.feidi.androidorder.util.DataCheckUtil;
import cn.didi.feidi.androidorder.util.MD5Util;

import static android.content.ContentValues.TAG;


public class FindBackPayPswByVerifyCodeFragment extends FeidiBaseFragment {

    private final static int FIRST_STEP = 1;
    private final static int SECOND_STEP = 2;

    private final static int FINISH = 3;
    private static final int REP_SEND_SMS = 1; //重新发送
    public String country = "86";//这是中国区号，如果需要其他国家列表，可以使用getSupportedCountries();获得国家区号
    //用于标识第三个步骤里的两个小步骤
    private int whereStep = FIRST_STEP;
    //注册账号的状态 1：第一步输入手机号 2：第二步输入验证码 3：第三步设置密码
    private int register_status = 1;
    private LinearLayout firstStepInputPhone;
    private LinearLayout secondStepInputVerifyNum;
    private LinearLayout threeStepInputNewPassword;
    private EditText inputPhone;
    private TextView toSecondStep;
    private EditText inputVerify;
    private TextView sendVerifyAgain;
    private TextView toThreeStep;
    private TextView secondStep;
    private TextView changePasswordTip;
    private TextView changePasswordTip2;
    private GridPasswordView gridPasswordView;
    private TextView saveNewPasswordBtn;
    //验证码
    private String verificationCode;
    //    电话号码
    private String phoneNumber;
    //    找回支付密码修改的签名
    private String sign;
    //    新密码
    private String newPasswordOne;
    private String newPasswordTwo;
    //    public String country="86";//这是中国区号，如果需要其他国家列表，可以使用getSupportedCountries();获得国家区号
    private int TIME = 60;//倒计时60s这里应该多设置些因为mob后台需要60s,我们前端会有差异的建议设置90，100或者120
    //时间倒计时
    private TimerTask tt;
    private Timer tm;
    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.arg1 == 1) {
//                cancelTimeCount();
//                makeToast("已发送验证码");
//                设置重新发送按钮不可以点击
                changeResentSmsButtonClickable(false);
            } else if (msg.arg1 == 2) {
//                makeToast("验证码获取失败");
                cancelTimeCount();

//                设置重新发送按钮可以点击
                changeResentSmsButtonClickable(true);
            } else if (msg.what == REP_SEND_SMS) {
                cancelTimeCount();
                TIME = 60;//时间重置

//                设置重新发送按钮可以点击
                changeResentSmsButtonClickable(true);
            } else {
                sendVerifyAgain.setText("重新发送" + "(" + TIME + ")");
            }
        }
    };


    /**
     * 与activity关联，后面可考虑单例模式
     *
     * @param bundle
     * @return
     */
    public static FindBackPayPswByVerifyCodeFragment newInstance(Bundle bundle) {
        FindBackPayPswByVerifyCodeFragment fragment = new FindBackPayPswByVerifyCodeFragment();
        if (bundle != null)
            fragment.setArguments(bundle);
        return fragment;
    }


    @Override
    protected View initFragment(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_find_back_pay_password_by_verify_code, container, false);
        return rootView;
    }

    @Override
    protected void initViews(View rootView) {
        firstStepInputPhone = (LinearLayout) rootView.findViewById(R.id.person_find_back_pay_psw_by_verify_first_step);
        secondStepInputVerifyNum = (LinearLayout) rootView.findViewById(R.id.person_find_back_pay_psw_by_verify_second_step);
        threeStepInputNewPassword = (LinearLayout) rootView.findViewById(R.id.person_find_back_pay_psw_by_verify_three_step);

        inputPhone = (EditText) rootView.findViewById(R.id.person_find_back_pay_psw_by_verify_phone_input);
        toSecondStep = (TextView) rootView.findViewById(R.id.person_find_back_pay_psw_by_verify_to_second_step);

        inputVerify = (EditText) rootView.findViewById(R.id.person_find_back_pay_psw_by_verify_verify_num);
        sendVerifyAgain = (TextView) rootView.findViewById(R.id.person_find_back_pay_psw_by_verify_send_again);
        toThreeStep = (TextView) rootView.findViewById(R.id.person_find_back_pay_psw_by_verify_to_three_step);
        secondStep = (TextView) rootView.findViewById(R.id.person_find_back_pay_psw_by_verify_second_step_tip);

        changePasswordTip = (TextView) rootView.findViewById(R.id.person_wallet_find_back_by_verify_pay_password_tip);
        changePasswordTip2 = (TextView) rootView.findViewById(R.id.person_wallet_find_back_by_verify_pay_password_tip2);
        gridPasswordView = (GridPasswordView) rootView.findViewById(R.id.person_wallet_find_back_pay_password_by_verify_gridpassword_view);
        saveNewPasswordBtn = (TextView) rootView.findViewById(R.id.person_find_back_pay_psw_by_verify_save_feidi_pay_password_btn);
    }

    @Override
    protected void initData() {
        //初始化第一步动作
        register_status = 1;
    }

    @Override
    protected void addListener() {
        toSecondStep.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                phoneNumber = inputPhone.getText().toString().trim();
                if (DataCheckUtil.isEmpty(phoneNumber) || !DataCheckUtil.isRightPhoneNumber(phoneNumber)){
                    showPhoneFalseDialog();
                    return;
                }
                firstStepInternetRequest();
            }
        });

        //使用手机号请求发送验证码 第二次发送验证码
        sendVerifyAgain.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (register_status) {
                    case 1:
                    case 2:
                        sendSms(phoneNumber);
                        break;
                    default:
                        break;
                }
            }
        });

        toThreeStep.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                verificationCode = inputVerify.getText().toString().trim();
                if (verificationCode.length()!=4){
                    showVerifyFalseDialog();
                    return;
                }

                verifyAndGetSign();
            }
        });

        gridPasswordView.setOnPasswordChangedListener(new GridPasswordView.OnPasswordChangedListener() {
            @Override
            public void onTextChanged(String psw) {

            }

            @Override
            public void onInputFinish(String psw) {
                if (whereStep == FIRST_STEP) {
                    newPasswordOne = psw;
                    gridPasswordView.clearPassword();
                    changePasswordTip.setText("再次填写以确认");
                    changePasswordTip2.setVisibility(View.GONE);
                    saveNewPasswordBtn.setVisibility(View.VISIBLE);
                    whereStep = SECOND_STEP;
                } else {
                    if (whereStep == SECOND_STEP) {
                        newPasswordTwo = psw;
                        if (!newPasswordOne.equals(newPasswordTwo)) {
                            makeToast("新密码输入不一致,请重新输入");
                            whereStep = FIRST_STEP;
                            gridPasswordView.clearPassword();
                            changePasswordTip.setText("请设定新密码");
                            changePasswordTip2.setVisibility(View.VISIBLE);
                            saveNewPasswordBtn.setVisibility(View.GONE);
                        } else {
                            InputMethodManager inputMethodManager = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                            if (inputMethodManager.isActive()) {
                                inputMethodManager.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(), 0);
                            }
                            saveNewPasswordBtn.setBackgroundColor(Color.parseColor("#347cf1"));
                            whereStep = FINISH;
                        }
                    }
                }
            }
        });

        gridPasswordView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (whereStep == FINISH) {
                    makeToast("不可再次编辑");
                }
            }
        });

        saveNewPasswordBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (whereStep == FINISH) {
                    setNewPayPasswordInServer();
                } else {
                    makeToast("请完整输入新密码");
                    return;
                }
            }
        });

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    private void showPhoneFalseDialog(){
        new CommomDialog(getContext(), R.style.dialog, "手机号输入错误", new CommomDialog.OnCloseListener() {
            @Override
            public void onClick(Dialog dialog, boolean confirm) {
                if (confirm) {
                    inputPhone.setText("");
                    dialog.dismiss();
                }
            }
        }, true, true).setPositiveButton("重新输入","#347cf1").show();
    }

    private void showVerifyFalseDialog(){
        new CommomDialog(getContext(), R.style.dialog, "短信验证码输入错误", new CommomDialog.OnCloseListener() {
            @Override
            public void onClick(Dialog dialog, boolean confirm) {
                if (confirm) {
                    inputVerify.setText("");
                    dialog.dismiss();
                }
            }
        }, true, true).setPositiveButton("重新输入","#347cf1").show();
    }

    /**
     * 设置提交按钮是否可见
     *
     * @param isClickable
     */
    private void changeResentSmsButtonClickable(boolean isClickable) {
        if (isClickable) {
//          设置重新发送按钮的样式
            sendVerifyAgain.setClickable(true);
            sendVerifyAgain.setText("重新发送");
        } else {
            sendVerifyAgain.setClickable(false);
            sendVerifyAgain.setTextColor(Color.parseColor("#999999"));
        }
    }

    /**
     * 发送验证码
     *
     * @param phoneNum
     */
    public void sendSms(String phoneNum) {
        switch (register_status) {
            case 1:
                // 通过sdk发送短信验证（请求获取短信验证码，在监听（eHandler）中返回）
                sendSMSRequest(phoneNum);
                tm = new Timer();
                tt = new TimerTask() {
                    @Override
                    public void run() {
                        mHandler.sendEmptyMessage(TIME--);
                    }
                };
                tm.schedule(tt, 0, 1000);
                break;
            case 2:
                // 通过sdk发送短信验证（请求获取短信验证码，在监听（eHandler）中返回）
                sendSMSRequest(phoneNum);
                tm = new Timer();
                tt = new TimerTask() {
                    @Override
                    public void run() {
                        mHandler.sendEmptyMessage(TIME--);
                    }
                };
                tm.schedule(tt, 0, 1000);

//                设置重新发送按钮不可点击
                changeResentSmsButtonClickable(false);

                break;
            default:
                break;
        }


    }

    private void firstStepInternetRequest(){
        sendSMSRequest(phoneNumber);
    }

    /**
     * 取消时间倒计时
     */
    private void cancelTimeCount() {
        if (tm != null)
            tm.cancel();//取消任务
        if (tt != null)
            tt.cancel();//取消任务
    }

    private void showSecondStep(){
        firstStepInputPhone.setVisibility(View.GONE);
        secondStepInputVerifyNum.setVisibility(View.VISIBLE);
        secondStep.setText("已发送验证码短信到您的手机 " + phoneNumber);
    }

    private void showThreeStep(){
        secondStepInputVerifyNum.setVisibility(View.GONE);
        threeStepInputNewPassword.setVisibility(View.VISIBLE);
    }

    //    得到此处找回支付密码的sign
    private void verifyAndGetSign() {
        Map<String, String> data = new HashMap<String, String>();
        data.put("userId", UserManager.getUserId());
        data.put("token", UserManager.getToken());
        data.put("phone", phoneNumber);
        data.put("verificationCode", verificationCode);

        executeRequest(new AppActionRequest<>(Api.FIND_BACK_PAY_PSW_BY_VERIFY_CHECK_PN, data, new TypeToken<ApiResponse<String>>() {
        }.getType(), new ActionCallbackListener<String>() {
            @Override
            public void onSuccess(String message, String data) {
                showThreeStep();
            }

            @Override
            public void onFailure(int errorEvent, String message) {
                Log.d(TAG, "errorEvent:" + errorEvent + "message=" + message);
                switch (errorEvent) {
                    case ErrorEvent.NONE_USER:
                        //不存在当前用户
                        break;
                    case ErrorEvent.WRONG_VERIFICATION_CODE:
                        makeToast("验证码不正确");
                        break;
                    case ErrorEvent.WRONG_PHONE_NUMBER:
                        makeToast("账号名为手机号");
                        break;
                    case ErrorEvent.PARAM_NULL:
                        makeToast("参数为空");
                        break;
                    case ErrorEvent.PARAM_ILLEGAL:
                        makeToast("参数为空");
                        break;
                    case ErrorEvent.PARAM_ACCESS_FAILURE:
                        makeToast("网络异常，访问失败");
                        break;
                    default:
                        makeToast("未知错误");
                        break;
                }
            }
        }));
    }

    private void setNewPayPasswordInServer() {
        Map<String, String> params = new HashMap<>();

        params.put("userId", UserManager.getUserId());
        params.put("token", UserManager.getToken());
        params.put("newPayPwd", MD5Util.GetMD5Code32Bit(newPasswordTwo));
        params.put("phone", phoneNumber);
        params.put("verificationCode", verificationCode);

        executeRequest(new AppActionRequest<>(Api.FIND_BACK_PAY_PWD_VERIFY_PN_SETPAY, params,
                new TypeToken<ApiResponse<String>>() {
                }.getType(), new ActionCallbackListener<String>() {
            @Override
            public void onSuccess(String message, String data) {
                makeToast("已设置新密码");
                getActivity().finish();
            }

            @Override
            public void onFailure(int errorEvent, String message) {
                Log.d(TAG, "errorEvent:" + errorEvent + "message=" + message);

                makeToast("密码设置失败");
                getActivity().finish();

                switch (errorEvent) {
                    case ErrorEvent.NONE_USER:
                        //不存在当前用户
                        break;
                    case ErrorEvent.WRONG_PHONE_NUMBER:
                        makeToast("账号名为手机号");
                        break;
                    case ErrorEvent.PARAM_NULL:
                        makeToast("参数为空");
                        break;
                    case ErrorEvent.PARAM_ILLEGAL:
                        makeToast("参数为空");
                        break;
                    case ErrorEvent.PARAM_ACCESS_FAILURE:
                        makeToast("网络异常，访问失败");
                        break;
                    default:
                        makeToast("未知错误");
                        break;
                }
            }
        }));
    }

    private void sendSMSRequest(String phoneNum) {
        Map<String, String> data = new HashMap<String, String>();
        data.put("userId", UserManager.getUserId());
        data.put("token", UserManager.getToken());
        data.put("phone", phoneNum);

        executeRequest(new AppActionRequest<String>(Api.FIND_BACK_PWD_CHECK_PN, data, new TypeToken<ApiResponse<String>>() {
        }.getType(), new ActionCallbackListener<String>() {
            @Override
            public void onSuccess(String message, String data) {
                showSecondStep();
                Message handlerMessage = mHandler.obtainMessage();
                handlerMessage.arg1 = 1;
                mHandler.sendMessage(handlerMessage);
            }

            @Override
            public void onFailure(int errorEvent, String message) {
                Log.d(TAG, "REGISTER failure errorEvent: " + errorEvent + "message: " + message);
                switch (errorEvent) {
                    case ErrorEvent.NONE_USER:
                        makeToast("该未注册");
                        break;
                    case ErrorEvent.WRONG_PHONE_NUMBER:
                        makeToast("手机号格式不对");
                        break;
                    case ErrorEvent.VERIFICATION_CODE_SAVE_ERROR:
                        makeToast("验证码保存失败");
                        break;
                    case ErrorEvent.VERIFICATION_CODE_SEND_ERROR:
                        makeToast("用户验证码发送失败");
                        break;
                    case ErrorEvent.NOT_YOUR_PHONE_NUMBER:
                        makeToast("未绑定该手机号");
                        break;
                    case ErrorEvent.PARAM_ACCESS_QUICK:
                        break;
                    case ErrorEvent.PARAM_ACCESS_ERROR_NET:
                        break;
                    default:
                        makeToast("捕捉到未知错误");
                        break;
                }
                Message handlerMessage = mHandler.obtainMessage();
                handlerMessage.arg1 = 2;
                mHandler.sendMessage(handlerMessage);
            }
        }));

    }
}
